
package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.demo.common.mq.MQListener;
import com.demo.common.mq.MessageSendTemplate;
import com.demo.common.mq.MqQueueConstants;
import com.demo.common.permission.PermissionService;
import com.demo.common.utils.JsonUtil;
import com.demo.entity.SysRolePermission;
import com.demo.entity.SysUser;
import com.demo.entity.vo.SysRolePermissionSaveReq;
import com.demo.mapper.SysRolePermissionMapper;
import com.demo.service.SysRolePermissionService;
import com.demo.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * serviceImpl
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper,SysRolePermission> implements SysRolePermissionService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private MessageSendTemplate messageSendTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRolePermission(SysRolePermissionSaveReq saveReq) {
        //删除老的角色权限
        this.remove(new QueryWrapper<SysRolePermission>().eq(SysRolePermission.ROLE_ID,saveReq.getRoleId()));
        List<SysRolePermission> sysRolePermissions = saveReq.getPermissions().stream().map(permission -> {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setRoleId(saveReq.getRoleId());
            sysRolePermission.setPermission(permission);
            return sysRolePermission;
        }).collect(Collectors.toList());
        //保存新的权限
        this.saveBatch(sysRolePermissions);
        //角色对应的人
        List<SysUser> sysUsers = this.sysUserService.list(new QueryWrapper<SysUser>().eq(SysUser
                .ROLE_ID, saveReq.getRoleId()));
        //清除关联用户的缓存，这里如果再优化一点，应该比较是否有角色权限是否有差异，再更新
        if(!CollectionUtils.isEmpty(sysUsers)){
            List<Integer> userIds = sysUsers.stream().map(SysUser::getId).collect(Collectors.toList());
            //走mq削峰
            messageSendTemplate.sendMsg(MqQueueConstants.ROLE_PERMISSION_UPDATE, JsonUtil.object2Json(userIds));
        }
    }

    /**
     * 清除角色关联用户缓存
     * @param msg
     */
    @MQListener(queue = MqQueueConstants.ROLE_PERMISSION_UPDATE)
    public void clearRoleUserPermission(String msg){
        List<Integer> userIds = JsonUtil.json2Object(msg, new TypeReference<List<Integer>>() {
        });
        permissionService.clearCache(userIds);
    }

    @Override
    public List<String> getUserPermission(Integer userId) {
        return this.baseMapper.selectPermission(userId);
    }

    @Override
    public List<String> getRolePermission(Integer roleId) {
        List<String> permissions = this.list(new QueryWrapper<SysRolePermission>().eq(SysRolePermission.ROLE_ID, roleId)).stream().map(SysRolePermission::getPermission).collect(Collectors.toList());
        return permissions;
    }
}
